package com.wchen.nio.capter2_3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

/**
 * @作者： wchen
 * @描述：
 * @创建时间： 2018/7/30 20:34
 * @版本：Copyright 2018, Inc. All Rights Reserved.
 * @修改信息：
 */
public class TimeServerHandle implements Runnable {

    private Socket socket;

    public TimeServerHandle(Socket socket) {
        this.socket = socket;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        BufferedReader bufferedReader = null;
        PrintWriter printWriter = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            printWriter = new PrintWriter(this.socket.getOutputStream(), true);
            String currentTime = null;
            String body = null;

            while (true){
                body = bufferedReader.readLine();
                if(body == null){
                    break;
                }
                System.out.println("The time server receiver order : " + body);
                currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ?
                        new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
                printWriter.println(currentTime);
            }
        }catch (IOException e){
            if(bufferedReader != null){
                try{
                    bufferedReader.close();
                }catch (IOException e1){
                    e1.printStackTrace();
                }
            }
            if(printWriter != null){
                 printWriter.close();
            }
            if(socket != null){
                try{
                    socket.close();
                }catch (IOException e1){
                    e1.printStackTrace();
                }
            }
            this.socket = null;
        }
    }
}
